import Taro, { Component } from '@tarojs/taro'
import { View,Image } from '@tarojs/components'
import { AtDivider, AtAvatar, AtInput, AtButton, AtGrid,AtActionSheet, AtActionSheetItem} from "taro-ui"
import './suifangdialog.css'
import touxiang from '../../../../img/touxiang.png'
import app from '../../../../main.js';

export default class Suifangdialog extends Component {

    config = {
        navigationBarTitleText: '周星星的咨询记录'
    }
    constructor () { 
        super(...arguments); 
        this.state = {
            style:'display:none',
            soundbtn:'display:none',
            inputBox:'display:block',
            value:'',
            pic:'',
            chatArr:app.chatArr,
            jiaB:'https://zhongsheng.bayou-tech.cn/img/imgs/jiaB.png',
            jianpangB:'https://zhongsheng.bayou-tech.cn/img/imgs/jianpangB.png',
            yuyinB:'https://zhongsheng.bayou-tech.cn/img/imgs/yuyinB.png',
            tp:'https://zhongsheng.bayou-tech.cn/img/imgs/tp.png',
            pz:'https://zhongsheng.bayou-tech.cn/img/imgs/pz.png',
            sp:'https://zhongsheng.bayou-tech.cn/img/imgs/sp.png',
            bd:'https://zhongsheng.bayou-tech.cn/img/imgs/biaodan.png',
            hj:'https://zhongsheng.bayou-tech.cn/img/imgs/huanjiao.png',
            kh:'https://zhongsheng.bayou-tech.cn/img/imgs/kuaihui.png',
            jh:'https://zhongsheng.bayou-tech.cn/img/imgs/jihua.png',
            icon:'https://zhongsheng.bayou-tech.cn/img/imgs/yuyinB.png',
            recordStatus:'',
            startTime:'',
            huanzheid:app.current.id,
            doctorid:app.doctorid,
            AtActionSheetOpen:false,
        }
    }

    display(){
        this.setState({
            style:'display:block',
            icon:this.state.yuyinB,
            soundbtn:'display:none',
            inputBox:'display:block',
        })
    }

    closeBox(){
        this.setState({
            style:'display:none',
        })
    }
    soundClick(){
        if(this.state.icon== this.state.yuyinB){
        this.setState({
            style:'display:none',
            icon:this.state.jianpangB,
            soundbtn:'display:block',
            inputBox:'display:none',
        });
        }else{
        this.setState({
            style:'display:none',
            icon:this.state.yuyinB,
            soundbtn:'display:none',
            inputBox:'display:block',
        });
        }
    }

    changvalue(value){
        this.setState({
            value:value
        })
    }

  	//跳转
	gotoIllness(){
		app.redirectTo('../Illness/Illness')
    }
    // 活动面板
    AtActionSheetClose(){
        this.setState({
            AtActionSheetOpen:false
        })
    }
    AtActionSheetItemClick(content){
        this.setState({
            value:content
        })
    }
    // grid选择
    changeGrid(a,id){
        switch(id){
            case 0 :
            this.uploadHeadImage()
            break;
            case 1:
            app.navigateTo('../howToPhotograph/howToPhotograph?id='+ '10')
            break;
            case 2:
            app.navigateTo('../step/step?id='+ '10')
            break;
            case 3:
            this.setState({
                AtActionSheetOpen:true
            })
            break;
            case 4:
            break;
            case 5:
            break;
            case 6:
            break;
        }
    }
    // 文本
    sendmessage(){
        let message = this.state.value
        let params = {
            type:'问诊订单',
            relate_id:3,
            sender_type:'患者',
            sender_id:2,
            receiver_type:'医生',
            receiver_id:2,
            content : {
                type:'text',
                data:message
            }
        }
        let chatArr = this.state.chatArr
        chatArr.push(params.content)
        app.chatArr = chatArr
        this.setState({
            chatArr:chatArr
        })
        
        let data = {
            token:0,
            params:JSON.stringify(params)
        }
        Taro.sendSocketMessage({ data: JSON.stringify({to: this.state.doctorid, type: "text", data: message, url: "http://www.baidu.com", params: params}) });
        app.post('web/instant_chat_record/create', data, function(res){
            console.log(res)
        })
        this.setState({
            value:''
        })
    }

    getmessage(){
        let data = {
            offset:0,
            length:20,
            type:'问诊订单',
            relate_id:3
        }
        app.get('web/instant_chat_record/many', data, function(res){
            console.log(res)
        })
    }
    // 语音
    startHandel(e) {
        console.log(22222);
        var that = this;
        var startTime = e.timeStamp;
        var recordStatus = that.state.recordStatus;
        if (!recordStatus){
          wx.getSetting({
            success(res) {
              if (!res.authSetting['scope.record']) {
                wx.authorize({
                  scope: 'scope.record',
                  success() {
                    recordStatus=true;
                    that.setState({
                      recordStatus: recordStatus
                    })
                  }
                })
              }
            }
          })
        }else{
          //记录开始录音时间
          that.setState({
            startTime: startTime
          })
          wx.showLoading({
            title: '开始录音',
            mask: true
          })
          recorderManager.onStart(() => {
            console.log('recorder start')
          })
          const options = {
            duration: 10000,
            sampleRate: 44100,
            numberOfChannels: 1,
            encodeBitRate: 96000,
            format: 'mp3',
            frameSize: 50
          }
          recorderManager.start(options);
        }
 
    }
    //松开按钮
    endHandle(e) {
          var that = this;
          var recordStatus = that.state.recordStatus;
          console.log(recordStatus);
          if (recordStatus){
            var endTime = e.timeStamp;
            var speakTime = endTime-that.state.startTime;
            //如果录音时间太短，提示
            if (speakTime < 350 ){
              wx.showToast({
                title: '说话时间太短',
                icon: 'none',
              })
              recorderManager.stop();
            }else{ 
                      wx.hideLoading();
                      wx.showToast({
                          title: '正在努力搜索',
                          icon: 'loading',
                          duration: 6000,
                          mask: true
                      })
                      recorderManager.onStop((res) => {
                          const { tempFilePath } = res;
                              //上传录制的音频
                              Taro.uploadFile({
                                    url: app.apiUri + '/admin/upload/image',
                                    filePath: tempFilePaths[0],
                                    name: 'file',
                                    formData: {
                                        name: 'file'
                                    },
                                    success(res) {
                                        let data = JSON.parse(res.data);
                                        if (data.status == 200) {             
                                            // app.eyesfile = data.result;
                                            console.log(data.result)
                                        }
                                    }
                                })
                      })
                      //触发录音停止
                      recorderManager.stop();
            }
          }
    }
    // 图片
    uploadHeadImage() {
        var me = this;
        Taro.chooseImage({
            count: 1,
            sizeType: ['original', 'compressed'],
            sourceType: ['album', 'camera'],
            success(res) {
                console.log(res);
                const tempFilePaths = res.tempFilePaths
                Taro.uploadFile({
                url: app.apiUri + '/admin/upload/image',
                filePath: tempFilePaths[0],
                name: 'file',
                formData: {
                    name: 'file'
                },
                success(res) {
                    let data = JSON.parse(res.data);
                    if (data.status == 200) {             
                        app.eyesfile = data.result;
                        me.setState({
                            pic:data.result
                        })
                        // console.log(data.result)
                        let message = data.result
                        let params = {
                            type:'问诊订单',
                            relate_id:3,
                            sender_type:'患者',
                            sender_id:2,
                            receiver_type:'医生',
                            receiver_id:2,
                            content : {
                                type:'image',
                                data:message
                            }
                        }

                        let chatArr = me.state.chatArr
                        chatArr.push(params.content)
                        app.chatArr = chatArr
                        me.setState({
                            chatArr:chatArr
                        })

                        let date = {
                            token:0,
                            params:JSON.stringify((params))
                        }
                        Taro.sendSocketMessage({ data: JSON.stringify({to: this.state.doctorid, type: "image", data: message, url: "http://www.baidu.com", params: params}) });
                        app.post('web/instant_chat_record/create', date, function(res){
                            console.log(res)
                        })
                    }
                }
                })
            }
        })
    }

    componentWillMount () { 
        if(this.$router.params.type == 'video'){
            let params = {
                type:'问诊订单',
                relate_id:3,
                sender_type:'患者',
                sender_id:2,
                receiver_type:'医生',
                receiver_id:2,
                content : {
                    type:'video',
                    data:app.eyesvideo
                }
            }

            let chatArr = this.state.chatArr
            chatArr.push(params.content)
            app.chatArr = chatArr
            this.setState({
                chatArr:chatArr
            })
            
            let data = {
                token:0,
                params:JSON.stringify((params))
            }
            Taro.sendSocketMessage({ data: JSON.stringify({to: this.state.doctorid, type: "video", data: message, url: "http://www.baidu.com", params: params}) });
            app.post('web/instant_chat_record/create', data, function(res){
                console.log(res)
            })
        }else
        if(this.$router.params.type == 'photo'){
            let params = {
                type:'问诊订单',
                relate_id:3,
                sender_type:'患者',
                sender_id:2,
                receiver_type:'医生',
                receiver_id:2,
                content : {
                    type:'image',
                    data:app.eyesphoto
                }
            }

            let chatArr = this.state.chatArr
            chatArr.push(params.content)
            app.chatArr = chatArr
            this.setState({
                chatArr:chatArr
            })
            
            let data = {
                token:0,
                params:JSON.stringify((params))
            }
            Taro.sendSocketMessage({ data: JSON.stringify({to: this.state.doctorid, type: "image", data: message, url: "http://www.baidu.com", params: params}) });
            app.post('web/instant_chat_record/create', data, function(res){
                console.log(res)
            })
        }else{
            app.chatArr = []
        }
        this.getmessage();
        var me = this;
        var task = Taro.connectSocket({
          url: 'ws://39.106.26.67:8889?id='+ this.state.huanzheid,
          success: function () { 
            console.log('connect success')
          }
        }).then(task => {
          
          task.onOpen(function () {
            console.log('onOpen')
            me.setState({task: task});
            // task.send({ data: 'xxx' })
          })
          task.onMessage(function (msg) {
            console.log('onMessage: ', JSON.parse(msg.data));
            let message = JSON.parse(msg.data)
            if(message.data != ''){
                let chatArr = me.state.chatArr
                chatArr.push({
                    type:message.type,
                    data:message.data,
                    send:1
                })
                app.chatArr = chatArr
                me.setState({
                    chatArr:chatArr
                })
            }
          })
          task.onError(function () {
            console.log('onError')
          })
          task.onClose(function (e) {
            console.log('onClose: ', e)
          })
        })
    }

    render () {
    // 快速回复内容
    let qshfArray = [
        {id:0,content:'您好，我现在不方便回复消息，稍后回复您。'},
        {id:1,content:'请将您的电子病历发给我'},
        {id:2,content:'康复的怎么样了？'},
        {id:3,content:'请简单描述下您的病况'}
    ]


    return (
      <View className='index'>
        <AtDivider className='divider'  content='本次咨询开始' fontColor='#8e8e8e' lineColor='#8e8e8e' />  
        <View className='time'> 2019-03-04 15:34 </View>

        <Form className='from' onClick={this.closeBox}>
            {
                this.state.chatArr.map((item)=>{
                    if(item.type == 'text' && item.send == undefined){
                        return(
                            <View className='textBox'>
                                <AtAvatar className='avatar' image={touxiang} />       
                                <View className='textview'>
                                    <View className='text'>{item.data}</View>
                                </View>
                            </View>
                        )
                    }else if(item.type == 'image' && item.send == undefined){
                        return(
                            <View className='textBox'>
                                <AtAvatar className='avatar' image={touxiang} />       
                                <View className='textview-c'>
                                    <Image mode='aspectFit' className='img-e' src={item.data} />
                                </View>
                            </View> 
                        )
                    }else if(item.type == 'photo' && item.send == undefined){
                        return(
                            <View className='textBox'>
                                <AtAvatar className='avatar' image={touxiang} />       
                                <View className='textview-c'>
                                    <Image mode='aspectFit' className='img-e' src={item.data} />
                                </View>
                            </View> 
                        )
                    }else if(item.type == 'video' && item.send == undefined){
                        return(
                            <View className='textBox'>
                                <AtAvatar className='avatar' image={touxiang} />       
                                <View className='textview-d'>
                                    <Video controls={true} className='video' src={item.data} />
                                </View>
                            </View> 
                        )
                    }else if(item.type == 'text' && item.send == 1){
                        return(
                            <View className='textBoxs'>
                                <AtAvatar className='avatar' image={touxiang} />       
                                <View className='textview'>
                                    <View className='text'>{item.data}</View>
                                </View>
                            </View>
                        )
                    }else if(item.type == 'image' && item.send == 1){
                        return(
                            <View className='textBoxs'>
                                <AtAvatar className='avatar' image={touxiang} />       
                                <View className='textview-c'>
                                    <Image mode='aspectFit' className='img-e' src={item.data} />
                                </View>
                            </View> 
                        )
                    }else if(item.type == 'photo' && item.send == 1){
                        return(
                            <View className='textBoxs'>
                                <AtAvatar className='avatar' image={touxiang} />       
                                <View className='textview-c'>
                                    <Image mode='aspectFit' className='img-e' src={item.data} />
                                </View>
                            </View> 
                        )
                    }else if(item.type == 'video' && item.send == 1){
                        return(
                            <View className='textBoxs'>
                                <AtAvatar className='avatar' image={touxiang} />       
                                <View className='textview-d'>
                                    <Video controls={true} className='video' src={item.data} />
                                </View>
                            </View> 
                        )
                    }             
                })
            }
        </Form>   

		<View className='empty' onClick={this.closeBox}></View>

		<View className='bottomBox'>
			<View className='inputBox'>
				<Image className='yuyin' src={this.state.icon} onClick={this.state.soundClick}></Image>
				<View className='atInput'>
					<AtInput onChange={this.changvalue} value={this.state.value} style={this.state.inputBox}></AtInput>
					<AtButton onTouchstart={this.startHandel} onTouchend={this.endHandle} className='btn' type='primary'style={this.state.soundbtn}>按住说话</AtButton>
				</View>
                {
                    this.state.value == '' 
                    ?
                    <Image className='jiaB' src={this.state.jiaB} onClick={this.display}></Image>
                    :
                    <View onClick={this.sendmessage} className='fasong'>发送</View>
                }
			</View>
			<View  className='closeBox' style={this.state.style}>
            <View className='t'>a</View>
            <AtGrid onClick={this.changeGrid.bind(this)} columnNum={4} data={
                    [
                        {
                            image:this.state.tp,
                            value: '图片'
                        },
                        {
                            image:this.state.pz,
                            value: '拍照'
                        },
                        {
                            image:this.state.sp,
                            value: '视频'
                        },
                        {
                            image:this.state.kh,
                            value:'快速回复'
                        },
                        {
                            image:this.state.hj,
                            value:'患教'
                        },
                        {
                            image:this.state.bd,
                            value:'表单'
                        },
                        {
                            image:this.state.jh,
                            value:'随访计划'
                        }
                    ]
                } />
            <AtActionSheet isOpened={this.state.AtActionSheetOpen} onClose={this.AtActionSheetClose}>
            {qshfArray.map((item)=>{
                return  <AtActionSheetItem onClick={this.AtActionSheetItemClick.bind(this,item.content)}>
                        {item.content}
                        </AtActionSheetItem>
            })
            }
            </AtActionSheet>
			</View>
		</View>

      </View>
    )
  }
}

